﻿using MaterialDemo.DataEntity;
using MaterialDemo.DataEntity.Entities;
using MaterialDemo.IService.IPermission;
using MaterialDemo.Model.RoleDTO;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MaterialDemo.Service.Permission
{
    public class RoleService : IRoleService
    {

        #region 构造函数注入
        private readonly ILogger<RoleService> _logger;

        private readonly DbContext _dbContext;
        public RoleService(ILogger<RoleService> logger, DbContext dbContext)
        //: base(dbContext)
        {
            _logger = logger;
            _dbContext = dbContext;

        }
        #endregion
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="inputModel"></param>
        /// <returns></returns>
        public int Add(RoleInput inputEntity)
        {

            RoleInfo entity = new RoleInfo
            {
                Id = inputEntity.Id,
                AddTime = DateTime.Now,
                DelFlag = 0,
                DelTime = DateTime.Now,
                Description = inputEntity.Description,
                RoleId = inputEntity.RoleId,
                RoleName = inputEntity.RoleName,
            };

            _dbContext.Set<RoleInfo>().Add(entity);
            return _dbContext.SaveChanges();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="inputModel"></param>
        /// <returns></returns>
        public int Update(RoleInput inputEntity)
        {
            RoleInfo entity = _dbContext.Set<RoleInfo>().Where(u => u.RoleId == inputEntity.RoleId).FirstOrDefault();
            if (entity != null)
            {
                entity.Description = inputEntity.Description;
                entity.RoleName = inputEntity.RoleName;
                _dbContext.Set<RoleInfo>().Attach(entity);
                _dbContext.Set<RoleInfo>().Update(entity);
                return _dbContext.SaveChanges();
            }
            else
            {
                return 0;
            }

        }

        /// <summary>
        /// 普通查询,获取未被禁用的所有
        /// </summary>
        /// <returns></returns>
        public List<RoleOutput> LoadEntities()
        {

            List<RoleOutput> list = (from a in _dbContext.Set<RoleInfo>().Where(u => u.DelFlag == 0)
                                         select new RoleOutput
                                         {
                                             Id = a.Id,
                                             AddTime = a.AddTime,
                                             DelFlag = a.DelFlag,
                                             DelTime = a.DelTime,
                                             Description = a.Description,
                                             RoleId = a.RoleId,
                                             RoleName = a.RoleName,
                                         }).ToList();

            return list;
        }

        /// <summary>
        /// 根据id查询
        /// </summary>
        /// <returns></returns>
        public List<RoleOutput> LoadEntities(int id)
        {
            List<RoleOutput> list = (from a in _dbContext.Set<RoleInfo>().Where(u => u.Id == id)
                                         select new RoleOutput
                                         {
                                             Id = a.Id,
                                             AddTime = a.AddTime,
                                             DelFlag = a.DelFlag,
                                             DelTime = a.DelTime,
                                             Description = a.Description,
                                             RoleId = a.RoleId,
                                             RoleName = a.RoleName,
                                         }).ToList();
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="s"></typeparam>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <param name="whereLambda"></param>
        /// <param name="orderbyLambda"></param>
        /// <param name="isAsc"></param>
        /// <returns></returns>
        public List<RoleOutput> LoadPageEntities(int pageIndex, int pageSize, out int totalCount, string selectInfo)
        {

            IQueryable<RoleInfo> iquery;
                 
            if (selectInfo == null || selectInfo == "")
            {
                totalCount = _dbContext.Set<RoleInfo>().Count();
                iquery = _dbContext.Set<RoleInfo>().OrderBy(u => u.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                totalCount = _dbContext.Set<RoleInfo>().Where(u => u.RoleName.Contains(selectInfo)).Count();
                iquery = _dbContext.Set<RoleInfo>().Where(u => u.RoleName.Contains(selectInfo)).OrderBy(u => u.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            List<RoleOutput> list = (from a in iquery
                                         select new RoleOutput
                                         {
                                             Id = a.Id,
                                             AddTime = a.AddTime,
                                             DelFlag = a.DelFlag,
                                             DelTime = a.DelTime,
                                             Description = a.Description,
                                             RoleId = a.RoleId,
                                             RoleName = a.RoleName,
                                         }).ToList();

            return list;

        }

        /// <summary>
        /// 获取用户拥有的角色
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public string GetRoleID(string userID)
        {
            var iquery = _dbContext.Set<RUserInfoRoleInfo>().Where(u => u.UserId == userID);
            //获取roleid-->（筛选被禁止的角色，严格来说，必须筛选）
            var roleIquery = _dbContext.Set<RoleInfo>().Where(u => u.Id > 0);
            var r_roleIquery = (from a in iquery
                                join b in roleIquery on a.RoleId equals b.RoleId into b_join
                                from c in b_join.DefaultIfEmpty()
                                select new
                                {
                                    UserID = a.UserId,
                                    RoleID = a.RoleId,
                                    DelFlag = c.DelFlag,
                                }).Where(u => u.DelFlag == 0);//筛选
                                                              //构造角色id字符串             
            if (r_roleIquery.Count() > 0)
            {
                string strRoleID = "";
                foreach (var item in r_roleIquery)
                {
                    strRoleID += item.RoleID + ",";
                }
                //去掉最后一个逗号               
                return strRoleID.Substring(0, strRoleID.Length - 1);
            }
            else
            {
                return "0";
            }
        }

        /// <summary>
        /// 给用户配置角色
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="arrRoleID"></param>
        /// <returns></returns>
        public bool ConfigRole(string userID, string arrRoleID)
        {       
            //分割
            string[] arrStr = arrRoleID.Split(',');
            //先查询要删除的数据                          
            List<RUserInfoRoleInfo> deletelist = _dbContext.Set<RUserInfoRoleInfo>().Where(u => u.UserId == userID).ToList();
            //打上批量删除的标记
            _dbContext.Set<RUserInfoRoleInfo>().RemoveRange(deletelist);

            //再查询需要添加的数据，装到addlist集合中
            List<RUserInfoRoleInfo> addlist = new List<RUserInfoRoleInfo>();
            for (int i = 0; i < arrStr.Length - 1; i++)
            {
                RUserInfoRoleInfo model = new RUserInfoRoleInfo
                {
                    UserId = userID,
                    RoleId = arrStr[i],
                };
                addlist.Add(model);
            }
            //打上批量添加的标记
            _dbContext.Set<RUserInfoRoleInfo>().AddRange(addlist);

            if (_dbContext.SaveChanges() > 0)//实现内置事务
            {

                return true;
            }
            else
            {
                return false;
            }


        }


        /// <summary>
        /// 开启/禁用角色
        /// </summary>
        /// <param name="id"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public bool ForbidRole(int id, string flag)
        {

            RoleInfo entity = _dbContext.Set<RoleInfo>().Where(u => u.Id == id).FirstOrDefault();
            if (entity != null)
            {
                if (flag == "true")
                {
                    entity.DelFlag = 0;//表示开启
                    _dbContext.Set<RoleInfo>().Attach(entity);
                    _dbContext.Set<RoleInfo>().Update(entity);
                    if (_dbContext.SaveChanges() > 0)
                    {
                        return true;
                    }
                }
                else
                {
                    entity.DelFlag = 1;//表示禁用
                    _dbContext.Set<RoleInfo>().Attach(entity);
                    _dbContext.Set<RoleInfo>().Update(entity);
                    if (_dbContext.SaveChanges() > 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// 判断RoleID是否重复,重复返回true
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool CheckRepeat(string roleID)
        {
            if (_dbContext.Set<RoleInfo>().Where(u => u.RoleId == roleID.Trim()).Count() > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
